<template>
  <view class="sxran-im-file-body" @click="downLoadFile" ref="sxran-im-file-body">
    <view class="file-msg-info">
      <text class="name">{{fileName}}</text>
      <text class="size">{{fileSize}}</text>
    </view>
    <sxran-im-icon name="file-text" />
  </view>
</template>

<script>
  export default {
    props: {
      msg: {
        type: Object,
        default () {
          return {
            body: ""
          }
        }
      },
    },
    computed: {
      fileSize() {
        if (this.msg.type == 'file') {
          let size = this.msg.body.size
          if (size < Math.pow(1024, 1)) {
            return parseInt(size * 10) / 10 + 'B'
          } else if (size < Math.pow(1024, 2)) {
            return parseInt(size / Math.pow(1024, 1) * 10) / 10 + 'KB'
          } else if (size < Math.pow(1024, 3)) {
            return parseInt(size / Math.pow(1024, 2) * 10) / 10 + 'MB'
          } else {
            return 'err'
          }
        }
        return 'err'
      },
      fileName() {
        if (this.msg.type == 'file') {
          let name = this.msg.body.name
          if (name.length < 30) {
            return name
          } else {
            return name.slice(0, 15) + '...' + name.slice(-15)
          }
        }
        return ''
      }
    },
    data() {
      return {

      }
    },
    methods: {
      async downLoadFile() {
        const url = await uniIm.utils.getTempFileURL(this.msg.body.url)
        // #ifdef H5
        return window.open(url)
        // #endif

        // #ifndef H5
        uni.downloadFile({
          url,
          success: (res) => {
            if (res.statusCode === 200) {
              // console.log('下载成功');
              // console.log(res.tempFilePath);
              uni.saveFile({
                tempFilePath: res.tempFilePath,
                success: (res) => {
                  // console.log('res',res);
                  uni.openDocument({
                    filePath: res.savedFilePath
                  })
                }
              });
            }
          }
        });
        // #endif
      },
    }
  }
</script>

<style scoped lang="scss">
  .sxran-im-file-body {
    background-color: var(--uni-bg-color-bubble);
    width: 500rpx;
    padding: 10px;
    border-radius: 8px;
    flex-direction: row;
    justify-content: space-between;
	align-items: center;
	display: flex;
    .file-msg-info {
      flex: 1;
	  display: flex;
      flex-direction: column;
      justify-content: space-around;
      .name {
        word-break: break-all;
		font-size: $uni-font-size-lg;
		color: var(--uni-text-color);
      }
      .size {
        font-size: $uni-font-size-sm;
        color: var(--uni-color-content);
      }
    }
    .file-icon {
    }
  }
</style>